/*
 * @Author: 姜斌
 * @Date: 2024-05-08 23:23:15
 * @LastEditTime: 2024-05-08 23:24:09
 * @LastEditors: 姜斌
 * @Description: 日志
 * @FilePath: \be_quna\router_handler\log.js
 */
const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const dayjs = require('dayjs');
const package = require('../package.json');
module.exports = (req, res) => {
    try {
        if (process.env.MODE === 'production' && req.query.show == '1' || process.env.MODE === 'development') {
            const folderPath = path.join(__dirname, '../log_box');
            res.render('log', { logs: filesList(folderPath, [], req), title: package.name, env_title: process.env.MODE === 'production' ? '生产环境' : '开发环境'})
        } else {
            res.send({ code: -1, msg: 'Danger!!!' })
        }
    } catch (error) {
        global.logger.error({ msg: error.message });
        res.send({ code: -1, msg: 'Danger!!!' })
    }
}

function formatBytes(bytes) {
    if (bytes < 1024) return bytes + ' Byte';
    else if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
    else if (bytes < 1024 * 1024 * 1024) return (bytes / 1024).toFixed(2) + ' MB';
    else return (bytes / 1024 / 1024 / 1024).toFixed(2) + ' GB';
}

function filesList(folderPath, arr, req) {
    if (fs.existsSync(folderPath)) {
        fs.readdirSync(folderPath).forEach((file) => {
            const curPath = path.join(folderPath, file);
            if (fs.lstatSync(curPath).isDirectory()) {
                filesList(curPath, arr, req);
            } else {
                const stats = fs.statSync(curPath);
                const relativePath = path.relative(process.cwd(), curPath);
                const protocol = req.headers['x-forward-proto'] || req.protocol;
                if (relativePath.includes(process.env.MODE)) {
                    arr.push({
                        name: file,
                        path: protocol + '://' + req.headers.host + path.sep + relativePath.split(path.sep).slice(1).join(path.sep),
                        size: formatBytes(stats.size),
                        folderName: relativePath.split(path.sep).slice(1,2),
                        ctime: dayjs(stats.ctime).format('YYYY-MM-DD HH:mm:ss'),
                        mtime: dayjs(stats.mtime).format('YYYY-MM-DD HH:mm:ss')
                    })
                }
            }
        })
    }
    return arr
}